#!/bin/sh

case "${DBMS}" in
    'postgres')
        test "$(PGPASSWORD="${POSTGRES_PASSWORD}" psql -Upostgres -hdb -tAc "select 1 from pg_database where datname='${SOCIAL_DB}'")" = "1"
        DB_EXISTS=$?
        ;;
    'mariadb')
        mysqlcheck -cqs -uroot -p"${MYSQL_ROOT_PASSWORD}" -hdb ${SOCIAL_DB} 2> /dev/null
        DB_EXISTS=$?
        exit 1
        ;;
    *)
        echo "Unknown DBMS"
        exit 1
esac

if [ ${DB_EXISTS} -ne 0 ]; then

    echo "Installing GNU social"
    echo "Installing composer dependencies"

    cd /var/www/social || exit 1

    composer -n install

    chmod g+w -R .
    chown -R :www-data .

    php bin/console doctrine:database:drop -f
    php bin/console doctrine:database:create
    php bin/console doctrine:schema:create      || exit 1
    php bin/console app:populate_initial_values || exit 1

    ./bin/install_plugins.sh

    echo "GNU social is installed"
else
    echo "GNU social is already installed"
fi
